package cn.group.service.impl;

import cn.group.domain.User;
import cn.group.service.UserService;
import cn.group.shiro.token.CustomizedToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Override
    public Map<String, Object> userLogin(String username, String password, String role) {
        Map<String, Object> map = new HashMap<>();
        //获取shiro系统中的当前用户
        Subject subject = SecurityUtils.getSubject();
        //判断是否认证
        if(!subject.isAuthenticated()){
            CustomizedToken token = new CustomizedToken(username,password,role);
            try{
                //执行验证
                subject.login(token);
            }catch (UnknownAccountException e){
                map.put("code",-2);
                map.put("message","查无此人");
                return map;
            }catch (IncorrectCredentialsException e){
                map.put("code",-3);
                map.put("message","密码输入错误");
                return map;
            }catch (AuthenticationException e){
                map.put("code",-1);
                map.put("message","登录失败");
                return map;
            }
        }
        //System.out.println("用户验证成功");
        User user = (User) subject.getSession().getAttribute("user");
        System.out.println("登录用户："+user);
        Jedis jedis = new Jedis("8.129.71.219",6379);
        map.put("user",user);
        map.put("code",0);
        map.put("message","登录成功");
        return map;
    }
}
